<template>
  <view class="expert-detail-container">
    <!-- 专家基本信息 -->
    <view class="expert-header">
      <view class="expert-avatar-section">
        <u-avatar :src="expert.avatar" size="80"></u-avatar>
        <view v-if="expert.isOnline" class="online-status">
          <view class="online-dot"></view>
          <text class="online-text">在线</text>
        </view>
      </view>
      
      <view class="expert-info">
        <view class="name-row">
          <text class="expert-name">{{ expert.name }}</text>
          <view v-if="expert.isVerified" class="verified-badge">
            <u-icon name="checkmark" size="12" color="white"></u-icon>
          </view>
        </view>
        <text class="expert-title">{{ expert.title }}</text>
        <text class="expert-hospital">{{ expert.hospital }}</text>
        
        <view class="rating-section">
          <view class="rating-stars">
            <u-icon 
              v-for="i in 5" 
              :key="i"
              name="star-fill" 
              size="16" 
              :color="i <= Math.floor(expert.rating) ? '#ffd700' : '#e0e0e0'"
            ></u-icon>
          </view>
          <text class="rating-text">{{ expert.rating }} ({{ formatCount(expert.consultCount) }}人咨询)</text>
        </view>
      </view>
    </view>
    
    <!-- 专家统计 -->
    <view class="expert-stats">
      <view class="stat-item">
        <text class="stat-value">{{ expert.experience }}</text>
        <text class="stat-label">从业年限</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ expert.goodRatePercent }}%</text>
        <text class="stat-label">好评率</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ expert.responseTime }}</text>
        <text class="stat-label">响应时间</text>
      </view>
    </view>
    
    <!-- 擅长领域 -->
    <view class="section">
      <view class="section-title">擅长领域</view>
      <view class="specialties-list">
        <view 
          v-for="(specialty, index) in expert.specialties" 
          :key="index"
          class="specialty-tag"
        >
          <text class="specialty-text">{{ specialty }}</text>
        </view>
      </view>
    </view>
    
    <!-- 专家介绍 -->
    <view class="section">
      <view class="section-title">专家介绍</view>
      <text class="expert-description">{{ expert.description || getDefaultDescription() }}</text>
    </view>
    
    <!-- 服务价格 -->
    <view class="section">
      <view class="section-title">咨询服务</view>
      <view class="service-list">
        <view class="service-item" @click="selectService('text')">
          <view class="service-info">
            <text class="service-name">图文咨询</text>
            <text class="service-desc">专家1对1图文解答，24小时内回复</text>
          </view>
          <view class="service-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ expert.textPrice }}</text>
          </view>
        </view>
        
        <view class="service-item" @click="selectService('voice')">
          <view class="service-info">
            <text class="service-name">语音咨询</text>
            <text class="service-desc">专家语音通话，实时沟通解答</text>
          </view>
          <view class="service-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ expert.voicePrice }}</text>
          </view>
        </view>
        
        <view class="service-item" @click="selectService('video')">
          <view class="service-info">
            <text class="service-name">视频咨询</text>
            <text class="service-desc">面对面视频通话，更直观的交流</text>
          </view>
          <view class="service-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ expert.videoPrice || expert.voicePrice + 20 }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 用户评价 -->
    <view class="section">
      <view class="section-title">
        <text>用户评价</text>
        <text class="review-count">({{ formatCount(reviewList.length) }}条)</text>
      </view>
      
      <view v-if="reviewList.length > 0" class="review-list">
        <view 
          v-for="(review, index) in reviewList.slice(0, 3)" 
          :key="index"
          class="review-item"
        >
          <view class="review-header">
            <u-avatar :src="review.userAvatar" size="32"></u-avatar>
            <view class="review-user-info">
              <text class="review-username">{{ review.username }}</text>
              <view class="review-rating">
                <u-icon 
                  v-for="i in 5" 
                  :key="i"
                  name="star-fill" 
                  size="12" 
                  :color="i <= review.rating ? '#ffd700' : '#e0e0e0'"
                ></u-icon>
              </view>
            </view>
            <text class="review-time">{{ formatTime(review.createTime) }}</text>
          </view>
          <text class="review-content">{{ review.content }}</text>
        </view>
        
        <view class="view-more-reviews" @click="viewAllReviews">
          <text class="view-more-text">查看全部评价</text>
          <u-icon name="arrow-right" size="14" color="#007aff"></u-icon>
        </view>
      </view>
      
      <view v-else class="no-reviews">
        <text class="no-reviews-text">暂无评价</text>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-buttons">
        <u-button 
          class="collect-btn"
          :class="{ collected: isCollected }"
          @click="toggleCollect"
        >
          <u-icon 
            :name="isCollected ? 'heart-fill' : 'heart'" 
            size="18" 
            :color="isCollected ? '#ff4757' : '#666'"
          ></u-icon>
          <text class="collect-text">{{ isCollected ? '已收藏' : '收藏' }}</text>
        </u-button>
        
        <u-button 
          type="primary" 
          class="consult-btn"
          @click="showConsultOptions"
        >
          立即咨询
        </u-button>
      </view>
    </view>
    
    <!-- 咨询方式选择弹窗 -->
    <u-popup 
      v-model="showServicePopup" 
      mode="bottom" 
      border-radius="20"
      :safe-area-inset-bottom="true"
    >
      <view class="service-popup">
        <view class="popup-header">
          <text class="popup-title">选择咨询方式</text>
          <u-icon name="close" size="20" color="#999" @click="showServicePopup = false"></u-icon>
        </view>
        
        <view class="popup-services">
          <view 
            v-for="service in consultServices" 
            :key="service.type"
            class="popup-service-item"
            @click="startConsultation(service.type)"
          >
            <view class="service-icon">
              <u-icon :name="service.icon" size="24" color="#007aff"></u-icon>
            </view>
            <view class="service-details">
              <text class="service-title">{{ service.name }}</text>
              <text class="service-subtitle">{{ service.description }}</text>
            </view>
            <view class="service-cost">
              <text class="cost-price">¥{{ service.price }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';

// 专家接口
interface Expert {
  id: string;
  name: string;
  avatar: string;
  title: string;
  hospital: string;
  specialties: string[];
  experience: number;
  rating: number;
  consultCount: number;
  goodRatePercent: number;
  responseTime: string;
  textPrice: number;
  voicePrice: number;
  videoPrice?: number;
  isVerified: boolean;
  isOnline: boolean;
  category: string;
  description?: string;
}

// 评价接口
interface Review {
  id: string;
  username: string;
  userAvatar: string;
  rating: number;
  content: string;
  createTime: string;
}

// 咨询服务接口
interface ConsultService {
  type: string;
  name: string;
  description: string;
  price: number;
  icon: string;
}

@Component
export default class ExpertDetailPage extends Vue {
  // 数据属性
  expertId: string = '';
  expert: Expert = {} as Expert;
  reviewList: Review[] = [];
  isCollected: boolean = false;
  showServicePopup: boolean = false;
  
  loading: boolean = false;
  
  // 计算属性
  get consultServices(): ConsultService[] {
    return [
      {
        type: 'text',
        name: '图文咨询',
        description: '专家1对1图文解答，24小时内回复',
        price: this.expert.textPrice || 0,
        icon: 'chat'
      },
      {
        type: 'voice',
        name: '语音咨询',
        description: '专家语音通话，实时沟通解答',
        price: this.expert.voicePrice || 0,
        icon: 'mic'
      },
      {
        type: 'video',
        name: '视频咨询',
        description: '面对面视频通话，更直观的交流',
        price: this.expert.videoPrice || (this.expert.voicePrice + 20) || 0,
        icon: 'camera'
      }
    ];
  }
  
  // 生命周期
  onLoad(options: any) {
    this.expertId = options.id || '';
    if (this.expertId) {
      this.loadExpertDetail();
      this.loadExpertReviews();
      this.checkCollectStatus();
    }
  }
  
  // 方法
  
  /**
   * 加载专家详情
   */
  async loadExpertDetail() {
    if (this.loading) return;
    
    this.loading = true;
    
    try {
      const response = await get(`/experts/detail/${this.expertId}`);
      this.expert = response.data.expert;
    } catch (error) {
      console.error('加载专家详情失败:', error);
      
      // 使用模拟数据
      this.expert = this.getMockExpert();
      
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.loading = false;
    }
  }
  
  /**
   * 加载专家评价
   */
  async loadExpertReviews() {
    try {
      const response = await get(`/experts/${this.expertId}/reviews`, {
        page: 1,
        pageSize: 10
      });
      this.reviewList = response.data.reviews || [];
    } catch (error) {
      console.error('加载评价失败:', error);
      
      // 使用模拟数据
      this.reviewList = this.getMockReviews();
    }
  }
  
  /**
   * 检查收藏状态
   */
  async checkCollectStatus() {
    try {
      const response = await get(`/experts/${this.expertId}/collect-status`);
      this.isCollected = response.data.isCollected || false;
    } catch (error) {
      console.error('检查收藏状态失败:', error);
    }
  }
  
  /**
   * 切换收藏状态
   */
  async toggleCollect() {
    // 检查登录状态
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.showModal({
        title: '提示',
        content: '请先登录后再收藏专家',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    try {
      if (this.isCollected) {
        await post(`/experts/${this.expertId}/uncollect`);
        this.isCollected = false;
        uni.showToast({
          title: '取消收藏',
          icon: 'success'
        });
      } else {
        await post(`/experts/${this.expertId}/collect`);
        this.isCollected = true;
        uni.showToast({
          title: '收藏成功',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 显示咨询选项
   */
  showConsultOptions() {
    // 检查登录状态
    const token = uni.getStorageSync('token');
    const isGuest = uni.getStorageSync('isGuest');
    
    if (!token && !isGuest) {
      uni.showModal({
        title: '提示',
        content: '请先登录后再咨询专家',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    if (isGuest) {
      uni.showToast({
        title: '游客模式无法咨询专家',
        icon: 'none'
      });
      return;
    }
    
    this.showServicePopup = true;
  }
  
  /**
   * 选择服务类型
   */
  selectService(type: string) {
    this.startConsultation(type);
  }
  
  /**
   * 开始咨询
   */
  startConsultation(type: string) {
    this.showServicePopup = false;
    
    // 跳转到支付页面
    uni.navigateTo({
      url: `/pages/payment/payment?expertId=${this.expertId}&serviceType=${type}`
    });
  }
  
  /**
   * 查看全部评价
   */
  viewAllReviews() {
    uni.navigateTo({
      url: `/pages/expert/reviews?expertId=${this.expertId}`
    });
  }
  
  /**
   * 格式化数量
   */
  formatCount(count: number): string {
    if (count < 1000) {
      return count.toString();
    } else if (count < 10000) {
      return (count / 1000).toFixed(1) + 'k';
    } else {
      return (count / 10000).toFixed(1) + 'w';
    }
  }
  
  /**
   * 格式化时间
   */
  formatTime(time: string): string {
    const date = new Date(time);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 30) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  }
  
  /**
   * 获取默认描述
   */
  getDefaultDescription(): string {
    return `${this.expert.name}医生从事${this.expert.category === 'pediatrics' ? '儿科' : '相关'}工作${this.expert.experience}年，具有丰富的临床经验。擅长${this.expert.specialties.join('、')}等领域，为众多家庭提供了专业的医疗咨询服务。`;
  }
  
  /**
   * 获取模拟专家数据
   */
  getMockExpert(): Expert {
    return {
      id: this.expertId,
      name: '张医生',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor&image_size=square',
      title: '主任医师',
      hospital: '北京儿童医院',
      specialties: ['新生儿护理', '儿童发育', '疫苗接种'],
      experience: 15,
      rating: 4.9,
      consultCount: 2580,
      goodRatePercent: 98,
      responseTime: '5分钟内',
      textPrice: 50,
      voicePrice: 80,
      videoPrice: 100,
      isVerified: true,
      isOnline: true,
      category: 'pediatrics',
      description: '张医生从事儿科工作15年，具有丰富的临床经验。擅长新生儿护理、儿童发育、疫苗接种等领域，为众多家庭提供了专业的医疗咨询服务。'
    };
  }
  
  /**
   * 获取模拟评价数据
   */
  getMockReviews(): Review[] {
    return [
      {
        id: '1',
        username: '新手妈妈',
        userAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20mother&image_size=square',
        rating: 5,
        content: '张医生非常专业，回复很及时，解答了我很多育儿疑问，非常感谢！',
        createTime: '2024-01-15T10:30:00Z'
      },
      {
        id: '2',
        username: '宝宝爸爸',
        userAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20father&image_size=square',
        rating: 5,
        content: '咨询了宝宝疫苗接种的问题，医生解答得很详细，很放心。',
        createTime: '2024-01-14T15:20:00Z'
      },
      {
        id: '3',
        username: '二胎妈妈',
        userAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=experienced%20mother&image_size=square',
        rating: 4,
        content: '医生很耐心，给出的建议很实用，推荐给其他妈妈。',
        createTime: '2024-01-13T09:45:00Z'
      }
    ];
  }
}
</script>

<style lang="scss" scoped>
.expert-detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.expert-header {
  background-color: white;
  padding: 40rpx 30rpx;
  display: flex;
  align-items: flex-start;
  
  .expert-avatar-section {
    position: relative;
    margin-right: 25rpx;
    
    .online-status {
      position: absolute;
      bottom: -5rpx;
      right: -5rpx;
      display: flex;
      align-items: center;
      background-color: #4caf50;
      border-radius: 20rpx;
      padding: 4rpx 8rpx;
      
      .online-dot {
        width: 8rpx;
        height: 8rpx;
        background-color: white;
        border-radius: 50%;
        margin-right: 4rpx;
      }
      
      .online-text {
        font-size: 18rpx;
        color: white;
      }
    }
  }
  
  .expert-info {
    flex: 1;
    
    .name-row {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;
      
      .expert-name {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        margin-right: 10rpx;
      }
      
      .verified-badge {
        width: 24rpx;
        height: 24rpx;
        background-color: #007aff;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .expert-title {
      display: block;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 8rpx;
    }
    
    .expert-hospital {
      display: block;
      font-size: 26rpx;
      color: #999;
      margin-bottom: 15rpx;
    }
    
    .rating-section {
      display: flex;
      align-items: center;
      
      .rating-stars {
        display: flex;
        margin-right: 10rpx;
      }
      
      .rating-text {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.expert-stats {
  background-color: white;
  margin-top: 20rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  
  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .stat-value {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.section {
  background-color: white;
  margin-top: 20rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    
    .review-count {
      font-size: 26rpx;
      color: #999;
      font-weight: normal;
      margin-left: 10rpx;
    }
  }
}

.specialties-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  
  .specialty-tag {
    background-color: #f0f8ff;
    border: 1rpx solid #007aff;
    border-radius: 20rpx;
    padding: 10rpx 20rpx;
    
    .specialty-text {
      font-size: 26rpx;
      color: #007aff;
    }
  }
}

.expert-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.service-list {
  .service-item {
    display: flex;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .service-info {
      flex: 1;
      
      .service-name {
        display: block;
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .service-desc {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .service-price {
      display: flex;
      align-items: baseline;
      
      .price-symbol {
        font-size: 24rpx;
        color: #ff4757;
        margin-right: 2rpx;
      }
      
      .price-value {
        font-size: 32rpx;
        font-weight: 600;
        color: #ff4757;
      }
    }
  }
}

.review-list {
  .review-item {
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .review-header {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;
      
      .review-user-info {
        flex: 1;
        margin-left: 15rpx;
        
        .review-username {
          display: block;
          font-size: 26rpx;
          color: #333;
          margin-bottom: 5rpx;
        }
        
        .review-rating {
          display: flex;
        }
      }
      
      .review-time {
        font-size: 22rpx;
        color: #999;
      }
    }
    
    .review-content {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
    }
  }
  
  .view-more-reviews {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 25rpx 0;
    
    .view-more-text {
      font-size: 26rpx;
      color: #007aff;
      margin-right: 8rpx;
    }
  }
}

.no-reviews {
  text-align: center;
  padding: 60rpx 0;
  
  .no-reviews-text {
    font-size: 26rpx;
    color: #999;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
    
    .collect-btn {
      flex: 0 0 120rpx;
      background-color: #f8f8f8;
      color: #666;
      border: none;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 80rpx;
      
      &.collected {
        background-color: #ffe6e6;
        color: #ff4757;
      }
      
      .collect-text {
        font-size: 22rpx;
        margin-top: 4rpx;
      }
    }
    
    .consult-btn {
      flex: 1;
      height: 80rpx;
      font-size: 32rpx;
      font-weight: 600;
    }
  }
}

.service-popup {
  background-color: white;
  border-radius: 20rpx 20rpx 0 0;
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .popup-services {
    padding: 20rpx 30rpx 40rpx;
    
    .popup-service-item {
      display: flex;
      align-items: center;
      padding: 25rpx 0;
      
      .service-icon {
        width: 60rpx;
        height: 60rpx;
        background-color: #f0f8ff;
        border-radius: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
      }
      
      .service-details {
        flex: 1;
        
        .service-title {
          display: block;
          font-size: 30rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .service-subtitle {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .service-cost {
        .cost-price {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff4757;
        }
      }
    }
  }
}
</style>